﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace Jsptpd.Common.DB
{
    public class UpdateOperation
    {
        #region Attribute
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(UpdateOperation));
        #endregion

        public void InsertDataRowIntoDatabase(DataRow dr)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("insert into jsptpd_crm..crm_project (");
            sb.Append("prjId,prjName,PrjCode) values (");
            sb.Append((GetInsertPrimaryKey() + 1) + ",'" + dr["项目名称"].ToString());
            sb.Append("','" + dr["项目编号"].ToString() + "')");
            DBHelper.executeNonQuery(sb.ToString());
            sb.Clear();
        }


        public void DataUpdateLogic(DataRow dr)
        {
            #region 对于已有项目的更新/对于新项目，直接更新到数据库
            string sql = "select count(*) from jsptpd_crm..crm_project where prjCode='" + dr["项目编号"].ToString() + "'";
            int RecordNum = Convert.ToInt32(DBHelper.GetDS(sql).Tables[0].Rows[0][0]);
            if (RecordNum < 1)
            {
                DBHelper.executeNonQuery(sql);
                InsertDataRowIntoDatabase(dr);
                logger.Info("添加项目：" + dr["项目名称"].ToString());
            }
            else
            {
                logger.Info(dr["项目名称"].ToString() + "已经存在");
            }
            #endregion


            #region 对于新项目，直接更新到数据库
            //InsertDataRowIntoDatabase(dr);
            #endregion

        }

        public int GetInsertPrimaryKey()
        {
            string sql = "select max(prjId) from jsptpd_crm..crm_project";
            DataSet ds = DBHelper.GetDS(sql);
            if (ds != null)
            {
                logger.Info("Get the table max key is:" + Convert.ToInt32(ds.Tables[0].Rows[0][0]));
                return Convert.ToInt32(ds.Tables[0].Rows[0][0]);
            }
            else
            {
                logger.Error("Get table 'crm_project' primary key failed!");
                return -1;
            }
        }
    }
}
